package com.im.netty.handler;

import static com.im.netty.protocol.Command.CREATE_GROUP_REQUEST;
import static com.im.netty.protocol.Command.GROUP_MESSAGE_REQUEST;
import static com.im.netty.protocol.Command.JOIN_GROUP_REQUEST;
import static com.im.netty.protocol.Command.LIST_GROUP_MEMBERS_REQUEST;
import static com.im.netty.protocol.Command.LOGOUT_REQUEST;
import static com.im.netty.protocol.Command.MESSAGE_REQUEST;
import static com.im.netty.protocol.Command.QUIT_GROUP_REQUEST;

import java.util.HashMap;
import java.util.Map;

import com.im.netty.handler.server.CreateGroupRequestHandler;
import com.im.netty.handler.server.GroupMessageRequestHandler;
import com.im.netty.handler.server.JoinGroupRequestHandler;
import com.im.netty.handler.server.ListGroupMembersRequestHandler;
import com.im.netty.handler.server.LogoutRequestHandler;
import com.im.netty.handler.server.MessageRequestHandler;
import com.im.netty.handler.server.QuitGroupRequestHandler;
import com.im.netty.protocol.Packet;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 
 * @author yutao
 */
public class IMHandler extends SimpleChannelInboundHandler<Packet> {

	public static final IMHandler INSTANCE = new IMHandler();
	
	private Map<Byte, SimpleChannelInboundHandler<? extends Packet>> handlerMap;
	
	private IMHandler() {
        handlerMap = new HashMap<>();

        handlerMap.put(MESSAGE_REQUEST, MessageRequestHandler.INSTANCE);
        handlerMap.put(CREATE_GROUP_REQUEST, CreateGroupRequestHandler.INSTANCE);
        handlerMap.put(JOIN_GROUP_REQUEST, JoinGroupRequestHandler.INSTANCE);
        handlerMap.put(QUIT_GROUP_REQUEST, QuitGroupRequestHandler.INSTANCE);
        handlerMap.put(LIST_GROUP_MEMBERS_REQUEST, ListGroupMembersRequestHandler.INSTANCE);
        handlerMap.put(GROUP_MESSAGE_REQUEST, GroupMessageRequestHandler.INSTANCE);
        handlerMap.put(LOGOUT_REQUEST, LogoutRequestHandler.INSTANCE);
    }
	
	/**
	 * 
	 * @see io.netty.channel.SimpleChannelInboundHandler#channelRead0(io.netty.channel.ChannelHandlerContext, java.lang.Object)
	 */
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Packet msg) throws Exception {
		
		SimpleChannelInboundHandler<? extends Packet> simpleChannelInboundHandler = handlerMap.get(msg.getCommand());
		
		simpleChannelInboundHandler.channelRead(ctx, msg);
	}

}
